import { defineStore } from "pinia";
import {
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import { type UserResult, loginPwd } from "@/api/admin";
import type { ResData } from "@/utils/http/types";
import { useMultiTagsStoreHook } from "./multiTags";
import {
  type DataInfo,
  setToken,
  removeToken,
  userKey,
  isMyPwdKey
} from "@/utils/auth";

export const useUserStore = defineStore("pure-user", {
  state: (): DataInfo => ({
    // 头像
    avatar: storageLocal().getItem<DataInfo>(userKey)?.avatar ?? "",
    // 用户名
    userName: storageLocal().getItem<DataInfo>(userKey)?.userName ?? "",
    // 昵称
    // token: storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? ""
    isMyPasswd: storageLocal().getItem<number>(isMyPwdKey) ?? 0
  }),
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.userName = username;
    },
    SET_IS_MY_PWD(pwd: number) {
      this.isMyPasswd = pwd;
    },
    // SET_TOKEN(token: string) {
    //   this.token = token;
    // },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<ResData<UserResult>>((resolve, reject) => {
        loginPwd(data)
          .then(res => {
            if (res.code === 0) setToken(res.data);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.userName = "";
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
